package com.lfs.apiController;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.lfs.annotations.ParameterValid;
import com.lfs.aspects.Parameter;
import com.lfs.common.cache.redis.base.MapCache;
import com.lfs.common.constant.CommonConstants;
import com.lfs.common.constant.Constant;
import com.lfs.common.utils.StringUtils;
import com.lfs.interfaces.agent.service.AgentSerivce;
import com.lfs.interfaces.dto.ResultReturn;
import com.lfs.interfaces.model.dto.ChargeDto;
import com.lfs.interfaces.model.vo.ChargeVo;
import com.lfs.interfaces.order.service.OrderBaseService;
import com.lfs.service.ApiChargeSerivce;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;

@RestController
@RequestMapping("/apiCharge")
public class ApiChargeController {

    private Logger logger = LoggerFactory.getLogger(ApiChargeController.class);

    @Resource
    private ApiChargeSerivce chargeSerivce;

    @Resource
    private OrderBaseService orderBaseService;

    @Resource
    private AgentSerivce agentSerivce;

    @Value("${bc.clientIps}")
    private String clientIps;

    @Resource
    private MapCache mapCache;

    /**
     * 创建支付请求接口
     *
     * @param parameter
     * @return
     * @throws Exception
     */
    @ParameterValid
    @PostMapping("/createCharge")
    @SentinelResource(value = "createCharge", blockHandler = "blockExceptionHandler")
    public ResultReturn<?> createCharge(@RequestBody Parameter parameter) {
        ResultReturn<ChargeVo> resp = new ResultReturn();
        ChargeVo chargeVO = new ChargeVo();
        chargeVO.setApplyTime(Constant.getDateTime());
        try {
            ChargeDto chargeDto = parameter.getObject(ChargeDto.class);
            resp = validParameter(chargeDto,chargeVO);
            if(null == resp || resp.getStatus().equals(CommonConstants.RESP_CHARGE_VALID_FAIL)){
                return  resp;
            }
            chargeVO.setReqStreamId(chargeVO.getReqStreamId());
            chargeVO.setExp1(chargeDto.getExp());
            long start = System.currentTimeMillis();
            chargeVO.setAgtPhone(chargeDto.getAgtPhone());
            chargeVO.setChargeNumBalance(chargeDto.getChargeMoney());
            resp = chargeSerivce.charge(chargeDto);
            logger.info("-----------总耗时为-----------" + (System.currentTimeMillis() - start));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            resp.setStatus(CommonConstants.RESP_CHARGE_EXCETION).setMsg("提交参数有误").setData(chargeVO);
        }
        logger.info("api充值响应客户端=[reqStreamId=" + resp.getData().getReqStreamId() + "&status=" + resp.getStatus() + "&msg="
                + resp.getMsg() + "]");
        return resp;
    }

    private ResultReturn validParameter(ChargeDto chargeDto,ChargeVo chargeVO){
        ResultReturn resp = new ResultReturn();
        if(null == chargeDto ){
            logger.error("请求的充值参数解析失败!");
            resp.setStatus(CommonConstants.RESP_CHARGE_VALID_FAIL).setMsg("提交参数有误").setData(chargeVO);
            return resp;
        }
        if(StringUtils.isBlank(chargeDto.getReqStreamId())){
            logger.error("请求的商户订单号不能为空!");
            resp.setStatus(CommonConstants.RESP_CHARGE_VALID_FAIL).setMsg("请求的商户订单号不能为空").setData(chargeVO);
            return resp;
        }
        if(StringUtils.isBlank(chargeDto.getChargeType())){
            logger.error("请求的充值类型不能为空!");
            resp.setStatus(CommonConstants.RESP_CHARGE_VALID_FAIL).setMsg("请求的充值类型不能为空").setData(chargeVO);
            return resp;
        }
        if(StringUtils.isBlank(chargeDto.getAgtPhone())){
            logger.error("请求的商户id不能为空!");
            resp.setStatus(CommonConstants.RESP_CHARGE_VALID_FAIL).setMsg("请求的商户id不能为空").setData(chargeVO);
            return resp;
        }
        if(null == chargeDto.getChargeMoney()){
            logger.error("请求的充值金额不能为空!");
            resp.setStatus(CommonConstants.RESP_CHARGE_VALID_FAIL).setMsg("请求的充值金额不能为空").setData(chargeVO);
            return resp;
        }
        logger.info("参数校验通过!");
        resp.setStatus(CommonConstants.RESP_CHARGE_VALID_SUCCESS).setMsg("请求的充值金额不能为空").setData(chargeVO);
        return resp;
    }

    public ResultReturn<?> blockExceptionHandler(@RequestBody Parameter parameter,BlockException e) {
        logger.error("服务接口限流,",e.getMessage());
        ResultReturn<ChargeVo> resp = new ResultReturn();
        resp.setStatus(CommonConstants.RESP_CHARGE_EXCETION).setMsg("系统繁忙,请稍后再试").setData(null);
        return resp;
    }

}
